//
//  UrbanRegistCollectionView.m
//  UrbanManagement
//
//  Created by Can on 18/4/9.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanRegistCollectionView.h"

@interface UrbanRegistCollectionView()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@end

@implementation UrbanRegistCollectionView


- (instancetype)initWithFrame:(CGRect)frame number:(NSInteger)number
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.frame = CGRectMake(frame.origin.x, frame.origin.y, SCREENW - frame.origin.x - 30*screenW_6, frame.size.height);
        
        _collectArray = [NSMutableArray new];
        
        _photoArray = [NSMutableArray new];
        
        _number = number;
        
        for (int i = 0; i < number; i++) {
            [_collectArray addObject:[UIImage imageNamed:@"add"]];
        }
        
        [self creatView];
    }
    return self;
}

- (void)creatView{
    //创建一个layout布局类
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //创建collectionView 通过一个布局策略layout来创建
    _registCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:layout];
    _registCollectionView.backgroundColor = [UIColor whiteColor];
    //代理设置
    _registCollectionView.delegate=self;
    _registCollectionView.dataSource=self;
    _registCollectionView.scrollEnabled = NO;
    //注册item类型 这里使用系统的类型
    [_registCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
    
    [self addSubview:_registCollectionView];
}

//返回分区个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//返回每个分区的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _collectArray.count;
}

//返回每个item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];

    UIImageView *imageView = [[UIImageView alloc]initWithImage:_collectArray[indexPath.row]];
    
    imageView.backgroundColor = [UIColor whiteColor];
    
    imageView.frame = CGRectMake(0, 0, 95*screenW_6, 95*screenW_6);
    
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    
    imageView.clipsToBounds = YES;
    
    imageView.userInteractionEnabled = YES;
    
    [cell addSubview:imageView];
    
    NSData *data1 = UIImagePNGRepresentation(_collectArray[indexPath.row]);
    NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"add"]);
    if (![data isEqual:data1]) {
        UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sanchu"]];
        imgView.frame = CGRectMake(imageView.frame.size.width - 30*screenW_6, 0, 30*screenW_6, 30*screenW_6);
        imgView.tag = indexPath.row;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImage:)];
        [imgView addGestureRecognizer:tapGesture];
        imgView.userInteractionEnabled = YES;
        [imageView addSubview:imgView];
    }
    
    return cell;
}

- (void)clickImage:(UITapGestureRecognizer *)tapView
{
    //替换数据源
    [_collectArray replaceObjectAtIndex:tapView.view.tag withObject:[UIImage imageNamed:@"add"]];
    //刷新数据
    [_registCollectionView reloadData];
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(95*screenW_6, 95*screenW_6);
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5*screenW_6, 5*screenW_6, 5*screenW_6, 5*screenW_6);
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_number == 2) {
        NSData *data1 = UIImagePNGRepresentation(_collectArray[indexPath.row]);
        NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"add"]);
        if ([data isEqual:data1]) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(homeWhere:)]) {
                [self.delegate homeWhere:indexPath.row];
            }
        }else{
            [self selectIndexRow:indexPath.row];
        }
    }else{
        if (_photoArray.count < _number) {

            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:_number - _photoArray.count delegate:nil];
            imagePickerVc.allowPickingVideo = NO;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets,BOOL isSelectOriginalPhoto) {
                
                for (UIImage *image in photos) {
                    //选择的图片放入数组
                    [self->_photoArray addObject:image];
                    
                }
                //替换数据源
                for (int i = 0; i < (int)self->_photoArray.count; i++) {
                    [self->_collectArray replaceObjectAtIndex:i withObject:self->_photoArray[i]];
                }
                //刷新数据
                [self->_registCollectionView reloadData];
                
            }];
            [[TomamaUI getTopVC] presentViewController:imagePickerVc animated:YES completion:nil];
        }
    }
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (void)selectIndexRow:(NSInteger)row
{
    //创建一个黑色背景
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    [backgroundView setBackgroundColor:[UIColor blackColor]];
    backgroundView.alpha = 0.7f;
    backgroundView.tag = 1000;
    UIApplication *ap = [UIApplication sharedApplication];
    [ap.keyWindow addSubview:backgroundView];
    
    //创建显示图像的视图
    //初始化要显示的图片内容的imageView
    UIImageView *browseImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    browseImgView.contentMode = UIViewContentModeScaleAspectFit;
    //要显示的图片，即要放大的图片
    browseImgView.image = _collectArray[row];
    browseImgView.tag = 1002;
    [ap.keyWindow addSubview:browseImgView];
    
    browseImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
    [browseImgView addGestureRecognizer:tapGesture1];
    
    [self shakeToShow:backgroundView];//放大过程中的动画
    [self shakeToShow:browseImgView];//放大过程中的动画
}

-(void)closeView{
    
    [[[UIApplication sharedApplication].keyWindow viewWithTag:1000] removeFromSuperview];
    
    [[[UIApplication sharedApplication].keyWindow viewWithTag:1002] removeFromSuperview];
}

//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.3;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
